package uia.alumni.useradm;

import java.io.IOException;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.UserTransaction;
import uia.alumni.data.Role;
import uia.alumni.data.User;
import uia.alumni.web.Command;



/**
 *
 * @author Even Åby Larsen (even.larsen@uia.no)
 */
public class SaveUser extends Command implements Constants {
    /** SERVLET_NAME is used for consistency checking of web.xml */
    public static final String SERVLET_NAME = "admin.saveuser";

    @PersistenceUnit(name=PERSISTENCE_UNIT)
    private EntityManagerFactory emf;

    @Resource
    private UserTransaction tx;


    public SaveUser() {
        super(Role.admin);
    }


    /** Save user data from the form created by EditUser */
    public void execute(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        long uid = parseLong(request.getParameter(UID), -1);
        String userName = request.getParameter(USERNAME);
        String password = request.getParameter(PASSWORD);
        String locked = request.getParameter(LOCKED);

        try {
            tx.begin();
            EntityManager em = emf.createEntityManager();
            User user = em.find(User.class, uid);
            if (user == null) { // new user
                // Check that name is unique
                Query q = em.createNamedQuery("User.findByName");
                q.setParameter("name", userName);
                user = (User)q.getSingleResult();
                if (user != null) throw new Exception("The username is not unique!");
                user = new User(userName, password);
                em.persist(user);
            }
            else {
                user.setUserName(userName);
                user.setPassword(password);
            }
            user.setLocked(locked != null);
            tx.commit();
        }
        catch (Exception e) {
            log("Save user failed", e);
            addMessage(request, "Saving user "+userName+" failed because: "+e.getMessage());
        }
        forwardTo(UserAdmin.SERVLET_NAME, request, response);
    }


    public final static long serialVersionUID = 1;
}
